<?php

class GebNutTask extends baseWemTask
{  
    public function configure()
    {
        parent::configure();
        $this->name      = 'GebNut';
        $this->briefDescription = 'Everything that arrives to an end had a beginning..';
                
        //ARGUMENTS
        $this->addArgument('plant',  sfCommandArgument::OPTIONAL,'Plant to check',0);
        $this->addArgument('start',  sfCommandArgument::OPTIONAL,'The starting day [Format: Y-m-d]',0);
        $this->addArgument('days',  sfCommandArgument::OPTIONAL,'Number of days to check [the greater the range the longer the script..] ',2);
        
    }
    public function execute($arguments = array(), $options = array())
    {
        //register log file
        $this->addFileLogger();
        
        //Get DB Connection
        $this->ConnectDB();
        
        //register task execution
        $tasklog=seth::regTaskStart($this->name, $arguments, $options );
        
        /*
         * ARGS VALIDATION
         */
        if ($arguments['plant']!=0){
            $plants=Doctrine_Core::getTable('plant')->findById($arguments['plant']);
            if (!is_object($plants)){
                $this->logBlock("The provided plant does not exist", "ERROR");
                seth::regTaskEnd($tasklog, false);
                die();
            }
        }       
        else{
            $plants=Doctrine_Core::getTable('Plant')->GetPlantIndex(array(
          "orderBy"=>"name",
          "indexOrder"=>"ASC"));
        }               
        /* TIME RANGE DEFINITION */
        if ($arguments["start"]==0)
            $dStart=0;
        elseif (strtotime($arguments["start"]) == FALSE){
            $this->logBlock("Argument [start] provided is not valid. Must be valid date","ERROR");
            seth::regTaskEnd($tasklog, false);
            die();
        }else
            $dStart=$arguments["start"];
            
        if (!is_numeric($arguments["days"]) or $arguments["days"]<=0){
            $this->logBlock("Argument [days] provided is not valid. Must be a number >0","ERROR");
            seth::regTaskEnd($tasklog, false);
            die();
        }else
            $days=$arguments["days"];
        
        if (Doctrine_Core::getTable("TaskLog")->countRunning($this->name)>0)
            Doctrine_Core::getTable("TaskLog")->stopHanged($this->name);
        
        $count=1;
        foreach ($plants as $p){
            if ($count>1)
                sleep(5);
            
            $sleep=0;
            $runnings=Doctrine_Core::getTable("TaskLog")->countRunning($this->name);
            while($runnings>30 and $sleep<150){
                sleep(2);
                //if (($sleep % 10)==0)
                if ($options["debug"])
                    $this->logBlock("Too many sons at work (".$runnings."). Waiting since ".($sleep*2)." secs [Max 300]. \tMem usage is: ".round(memory_get_usage()/1024,2). "KB", "INFO"); 
                $runnings=Doctrine_Core::getTable("TaskLog")->countRunning($this->name);
                $sleep++;
            }
            
            if (!Doctrine_Core::getTable("TaskLog")->isBusy($p->getId(),$this->name)){
                $args=$p->getId()." ".$dStart." ".$days;
                
                $drivers=  sfConfig::get('app_acq_systems');
                $sources=$p->getPowerdevSources();
                if ($sources!==FALSE){
                    if (strpos($sources[0], "Sam")!==FALSE)
                        $source=sfConfig::get('app_sam_pref_acq_system');
                    else    
                        $source=$sources[0];
                    $driver=$drivers[$source];
                    
                    
                    $this->logBlock("Generating a son for ".$p->getName(), "INFO");
                    $tr=exec(sfConfig::get("sf_root_dir")."/symfony wem:".$driver." ".$args." && ".sfConfig::get("sf_root_dir")."/symfony wem:procKpiDay ".$args);
                    $count++;
                    $this->logBlock("Son finished working on ".$p->getName()."\tMem usage is: ".round(memory_get_usage()/1024,2). "KB", "INFO");
                }else{
                    $this->logBlock(" No monitoring system source active for ".$p->getName().". Skip plant. ", "ERROR");
                }
            }else
                $this->logBlock(" Someone is already working on ".$p->getName().". Skip plant. ", "ERROR");
            
        }
        
        seth::regTaskEnd($tasklog, TRUE);        
    }
}